//
//  AudioImageSlideAndButtonsViewController.m
//  ubixar-framework
//
//  Created by Demis Bellot on 24/04/2009.
//  Copyright 2009 Ubixar. All rights reserved.
//

#import "AudioImageSlideAndButtonsViewController.h"

#define LOGGER 1 << 21
#define INFINITE_LOOPS -1

@implementation AudioImageSlideAndButtonsViewController

- (id)initWithCoder:(NSCoder *)coder {		
	if (self = [super initWithCoder:coder]) {
		DLog(@"initializing Audio");
	}
	return self;
}

- (void)setImageNames:(NSArray*)imageNames
		   audioNames:(NSArray*)theAudioNames
		  buttonNames:(NSArray*)buttonNames
	 firstButtonFrame:(CGRect)firstButtonFrame
		buttonPadding:(CGPoint)buttonPadding
{
	audioFileNames = [[NSMutableArray arrayWithArray:theAudioNames] retain];

	[super setImageNames:imageNames 
			 buttonNames:buttonNames 
		firstButtonFrame:firstButtonFrame 
		   buttonPadding:buttonPadding];
}

- (void) playAudio {
	
	if (audioPlayer) 
	{
		[self disposeAudioPlayer];
	}
	
	NSString* resourcePath = [[NSBundle mainBundle] resourcePath];
	resourcePath = [resourcePath stringByAppendingFormat:@"/%@", [self currentAudioFileName]];
	SILog(LOGGER, @"Path to play: %@", resourcePath);
	NSError* err;
	
	//Initialize our player pointing to the path to our resource
	audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:resourcePath] error:&err];
	
	//set the audioPlayer to be on repeat
	audioPlayer.numberOfLoops = INFINITE_LOOPS;
	
	if (err)
	{
		SELog(LOGGER, @"Failed with reason: %@", [err localizedDescription]);
	}
	else
	{
		//set our delegate, flip the button and let the magic happen
		audioPlayer.delegate = self;
		[audioPlayer play];
	}	
}

- (void) pauseAudio {
	[audioPlayer pause];
}

- (void)imageButtonWasPressed: (UIButton*)button {
	//set the selectedIndex
	[super imageButtonWasPressed:button];
	
	if (lastSelectedButton.selected)
	{
		[self playAudio];
	}
	else
	{
		[self pauseAudio];
	}
}

- (NSString*) currentAudioFileName{
	DLog(@"getting audioFileNames at %d", selectedIndex);
	return (NSString*) [audioFileNames objectAtIndex:selectedIndex];
}

- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)aplayer successfully:(BOOL)flag {
}

- (void)audioPlayerDecodeErrorDidOccur:(AVAudioPlayer *)player error:(NSError *)error {
	SLog(@"Error while decoding: %@", [error localizedDescription] );
}

- (void)audioPlayerBeginInterruption:(AVAudioPlayer *)player {
	DLog(@"Interrupted!");
}

- (void)audioPlayerEndInterruption:(AVAudioPlayer *)player {
	DLog(@"EndInterruption!");
}

- (void)disposeAudioPlayer {
	if (audioPlayer) 
	{
		[audioPlayer stop];
		[audioPlayer release];
		audioPlayer = nil;
	}	
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning]; // Releases the view if it doesn't have a superview
    // Release anything that's not essential, such as cached data
}


- (void)dealloc {
	[audioFileNames release];
	[self disposeAudioPlayer];
    [super dealloc];
}


@end
